package com.feijiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feijiang.entity.Experiment;
import com.feijiang.mapper.ExperimentMapper;
import com.feijiang.service.IExpeDataService;
import com.feijiang.service.IExpeRecordService;
import com.feijiang.service.IExpeStepService;
import com.feijiang.service.IExperimentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feijiang.util.MyPage;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-12-28
 */
@Service
@Slf4j
public class ExperimentServiceImpl extends ServiceImpl<ExperimentMapper, Experiment> implements IExperimentService {

  @Resource
  ExperimentMapper experimentMapper;

  @Resource
  IExpeStepService iExpeStepService;

  @Resource
  IExpeRecordService iExpeRecordService;

  @Resource
  IExpeDataService iExpeDataService;


  @Override
  public boolean add(Experiment experiment) {
    Assert.isTrue(!existName(experiment.getName()), "实验名称已存在");
    int insert = experimentMapper.insert(experiment);
    return insert > 0;
  }

  @Override
  public boolean edit(Experiment experiment) {
    int update = experimentMapper.updateById(experiment);
    return update > 0;
  }

  @Override
  public boolean delete(int exprId) {
    // 先删除其他关联的对象
    int i = iExpeStepService.deleteByExprId(exprId);
    log.info("删除了实验步骤{}条", i);

    int j = iExpeRecordService.deleteByExprId(exprId);

    boolean b = iExpeDataService.deleteByExpeId(exprId);

    int delete = experimentMapper.deleteById(exprId);
    log.info("删除了实验信息{}条", delete);
    return delete > 0;
  }

  @Override
  public MyPage list(int pageSize, int pageNum) {
    List<Experiment> experimentList = experimentMapper.list(pageSize, (pageNum - 1) * pageSize);
    return MyPage.buildPage(pageSize, pageNum, this.count(), experimentList);
  }

  @Override
  public boolean exist(int id) {
    Experiment experiment = this.getById(id);
    // 断言成立了，代码才往下走
    Assert.notNull(experiment, "id：" + id +"对应的实验信息不存在");
    return true;
  }

  @Override
  public Experiment getById(int id) {
    return this.experimentMapper.selectById(id);
  }

  @Override
  public List<Experiment> search(String keyword) {
    return experimentMapper.search(keyword);
  }

  /**
   * 查询实验名称是否存在
   * @param name
   * @return
   */
  private boolean existName(String name) {
    QueryWrapper<Experiment> experimentQueryWrapper = new QueryWrapper<>();
    experimentQueryWrapper.eq("name", name);
    Experiment experiment = experimentMapper.selectOne(experimentQueryWrapper);
    return experiment != null;
  }
}
